<script setup lang="ts">
  import { onMounted, ref, onBeforeUnmount, watch } from "vue";
  import { tinymce, plugins, Editor } from "./tinymce";
  const
    props = defineProps({
      modelValue: { type: String, default: "" },
    }),
    pp = "data:image/jpeg;base64,",
    entity = ref<HTMLDivElement>(),
    id = ref(`rich${unid}`),
    emit = defineEmits<{ (event: "update:modelValue", value: string): void; }>();
  let editor: Editor;

  function clear() {
    Object.keys(localStorage).forEach(k => {
      if (!k.indexOf("tinymce")) {
        localStorage.removeItem(k);
      }
    });
  }
  async function init() {
    if (entity.value) {
      tinymce.init({
        setup(e) {
          editor = e;
          editor.on("blur", () => {
            emit("update:modelValue", editor.getContent());
            next(() => { clear(); editor.setContent(props.modelValue); });
          });
          editor.on("focus", () => {
            clear();
            editor.setContent(props.modelValue);
          });
        },
        selector: "textarea#" + id.value, //富文本编辑器的id,
        language: "zh_CN",
        plugins: Object.keys(plugins), //这里的数据是在props里面就定义好了的
        license_key: "gpl",
        branding: false, // 是否禁用“Powered by TinyMCE”
        promotion: false, // 去掉 Upgrade
        quickbars_selection_toolbar: "bold italic| forecolor backcolor | quicklink h2 h3 blockquote quickimage quicktable", // 选中文字快捷提醒
        popup_zindex: "9999",
        //图片上传
        // images_upload_base_path: pp,
        // images_upload_url: apiUrl + "upload",
        async images_upload_handler(blobInfo) {
          return pp + blobInfo.base64();
        },
      });
    } else { next(init); }
  }
  onMounted(init);
  onBeforeUnmount(() => {
    editor?.destroy();
  });
  watch(() => props.modelValue, (n) => {
    editor?.setContent(n);
  }, { immediate: true });
  defineExpose({
    async upload(uploadMethod: (base64: string) => Promise<string>) {
      let c = editor.getContent();
      const reg = new RegExp(`(${pp}[^"]+)`, "g");
      const r = c.matchAll(reg);
      Object.assign(globalThis, { c, reg, pp });
      while (true) {
        const e = r.next();
        if (e.value) {
          const s = e.value[1];
          c = c.replace(s, await uploadMethod(s));
        } else {
          break;
        }
      }
      c = c.replaceAll(/<img src="([^"]+)"[^>]*>/g, '<img src="$1" style="width:100%;" />');
      emit("update:modelValue", c);
      return c;
    }
  });
</script>
<template>
  <div class="Rich whf y oh1" ref="entity">
    <textarea :id="id" :value="modelValue" />
  </div>
</template>
<style lang="scss" scoped>
  .Rich {
    position: relative;
    :nth-child(2) {
      height: 100% !important;
    }
  }
</style>